package org.xukai.remoting.ws;

import java.io.ByteArrayOutputStream;
import java.io.StringReader;
import java.net.URL;
import java.util.concurrent.Future;

import javax.xml.namespace.QName;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Source;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;
import javax.xml.ws.Dispatch;
import javax.xml.ws.Response;
import javax.xml.ws.Service;
import javax.xml.ws.soap.SOAPBinding;

import org.apache.cxf.endpoint.Client;
import org.apache.cxf.jaxws.endpoint.dynamic.JaxWsDynamicClientFactory;
import org.apache.cxf.transport.http.HTTPConduit;
import org.apache.cxf.transports.http.configuration.HTTPClientPolicy;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;

public class Mispservice {
//	String wsdlPrefix = "http://115.238.43.106:8090/himapws/webservice!viewWsdl.action?serviceName=";
//	String endpoint = "http://115.238.43.106:8090/himapws/webServices/himapEntryPort";
	String nsPrefix = "http://ws.server.himap.com/";
	String serviceName = "himapEntryService";
	String portName = "himapEntryPort";
	public static   String ipurl="http://127.0.0.1:8076";
	public static void main(String[] args) {
		String method = "demo";
		StringBuffer param = new StringBuffer("<startdate>20151001</startdate>");
//		param.append("<PageSize>2</PageSize>");
//		param.append("<PageIndex>1</PageIndex>");
		try {
			
			String tresult =  new Mispservice().invoke(method, param.toString(),ipurl);
			System.out.println(tresult);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}


	public static void main3(String[] args) throws Exception {
		String wsdl="http://115.238.43.106:8090/mispservice/alonewsflow/getWsdlContent/VD_pro_lab_count_total";
		String method="VD_pro_lab_count_total";
		String requestStr = "<RECORD_DATE>20161130</RECORD_DATE>"
				+ "<NAME></NAME>" +
				" <FLAG>" +0+ "</FLAG>";
		JaxWsDynamicClientFactory factory = JaxWsDynamicClientFactory.newInstance();
		Client client = factory.createClient(wsdl);
		HTTPConduit conduit = (HTTPConduit) client.getConduit();
		HTTPClientPolicy policy = new HTTPClientPolicy();
		long timeout = 10 * 60 * 1000;//
		policy.setConnectionTimeout(timeout);
		policy.setReceiveTimeout(timeout);
		conduit.setClient(policy);
		//动态invoke方法
		Object[] os =client.invoke(method,requestStr);
		System.out.println(os.length);

	}
	public String invoke(String method, String param, String ipurl)
			throws Exception {
		String wsdlPrefix=ipurl+"/alonewsflow/getWsdlContent/";
		String endpoint=ipurl+"/webServices/himapEntryPort";
		String wsdlUrl=wsdlPrefix + method+"";
		String ns =nsPrefix + method;
		System.out.println("wsdlPrefix="+wsdlPrefix);
		System.out.println("endpoint="+endpoint);
		System.out.println("wsdlUrl="+wsdlUrl);
		System.out.println("ns="+ns);
		URL wsdlURL = new URL(wsdlUrl);
		QName port = new QName(ns, portName);
		Source response = null;
		try {
			Service service = Service.create(wsdlURL,
					new QName(ns, serviceName));
			service.addPort(port, SOAPBinding.SOAP11HTTP_BINDING, endpoint);
			Dispatch<Source> disp = service.createDispatch(port, Source.class,
					Service.Mode.PAYLOAD);
			String request = String
					.format("<ns2:%1$s_Request xmlns:ns2=\"%2$s\"><request>%3$s</request></ns2:%1$s_Request>",
							method, ns, param);
			response = disp.invoke(new StreamSource(new StringReader(request)));
		} catch (Exception e) {
			e.printStackTrace();
			System.out.println("根据wsdl调用webservice中方法出现异常，可能是超时了");
			return "接口异常";
		}
		return sourceToXMLString(response);

	}


	public String invokeAsyc(String method, String param, String ipurl)
			throws Exception {
		String wsdlPrefix=ipurl+"/alonewsflow/getWsdlContent/";
		String endpoint=ipurl+"/webServices/himapEntryPort";
		String wsdlUrl=wsdlPrefix + method+"";
		String ns =nsPrefix + method;
		System.out.println("wsdlPrefix="+wsdlPrefix);
		System.out.println("endpoint="+endpoint);
		System.out.println("wsdlUrl="+wsdlUrl);
		System.out.println("ns="+ns);
		URL wsdlURL = new URL(wsdlUrl);
		QName port = new QName(ns, portName);
		Source response = null;
		try {
			Service service = Service.create(wsdlURL,
					new QName(ns, serviceName));
			service.addPort(port, SOAPBinding.SOAP11HTTP_BINDING, endpoint);
			Dispatch<Source> disp = service.createDispatch(port, Source.class,
					Service.Mode.PAYLOAD);
			String request = String
					.format("<ns2:%1$s_Request xmlns:ns2=\"%2$s\"><request>%3$s</request></ns2:%1$s_Request>",
							method, ns, param);
			Future<Source> future = disp.invokeAsync(new StreamSource(new StringReader(request)));
			Response<Source> sourceResponse = disp.invokeAsync(new StreamSource(new StringReader(request)));
		} catch (Exception e) {
			e.printStackTrace();
			System.out.println("根据wsdl调用webservice中方法出现异常，可能是超时了");
			return "接口异常";
		}
		return sourceToXMLString(response);

	}


	public String sourceToXMLString(Source result) throws Exception {
		String xmlResult = null;
		TransformerFactory factory = TransformerFactory.newInstance();
		Transformer transformer = factory.newTransformer();
		transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
		transformer.setOutputProperty(OutputKeys.METHOD, "xml");

		ByteArrayOutputStream out = new ByteArrayOutputStream();
		StreamResult streamResult = new StreamResult();
		streamResult.setOutputStream(out);

		transformer.transform(result, streamResult);
		xmlResult = out.toString("UTF-8");
		return xmlResult;
		/*Document document = DocumentHelper.parseText(xmlResult);
		Element rootElement = document.getRootElement();
		String patientsInfo = rootElement.element("response").element("Body").getText();
		return patientsInfo;*/
	}
}
